﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BalanceControl.Comm.Codec
{
    public class FixLengthWithHeaderCodec : ICodec
    {
        private enum DecoderState
        {
            Idle,
            Ready,
            Receving,
        }

        private int frameLength;
        private Byte[] _recBuff;
        private int _recptr = 0;//数据指针
        private DecoderState _state = DecoderState.Idle;//当前解析状态

        public FixLengthWithHeaderCodec(int frameLen)
        {
            frameLength = frameLen;
            _recBuff = new Byte[frameLength];//数据缓冲
        }

        private void decode(byte b, ref List<Object> result)
        {
            switch (_state)
            {
                case DecoderState.Idle:
                    if (b == 0x55)
                    {
                        _recptr = 0;
                        _recBuff[_recptr++] = b;
                        _state = DecoderState.Ready;
                    }
                    //else
                    //{
                    //    LogHelper.WARNING("接收到错误数据：" + data.ToString("X2"));
                    //}
                    break;
                case DecoderState.Ready:
                    _recBuff[_recptr++] = b;
                    if (_recptr > (frameLength - 1))
                    {
                        _state = DecoderState.Idle;
                        byte[] recData = new byte[frameLength];
                        _recBuff.CopyTo(recData, 0);
                        result.Add(recData);
                        //FrameReceivedCB(recData);
                    }
                    break;
                case DecoderState.Receving:
                    break;
            }

        }

        #region 接口
        public List<Object> decode(List<Object> input)
        {
            List<Object> result = new List<object>();
            foreach (Object obj in input)
            {
                if (obj is byte[])
                {
                    byte[] databuffer = obj as byte[];
                    foreach (byte b in databuffer)
                    {
                        decode(b, ref result);
                    }
                }
            }
            return result;
        }

        public List<Object> encode(List<Object> input)
        {
            return null;
        }

        #endregion

    }
}
